package com.fz.us.oa.web.controller.main.company;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.Result;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.SearchEnum;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.page.PageHelp;
import com.fz.us.admin.base.bean.search.result.SearchResultList;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.bean.search.rule.Rule;
import com.fz.us.admin.company.entity.*;
import com.fz.us.admin.company.service.DepartmentService;
import com.fz.us.admin.company.service.PostService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 控制器 - 岗位信息
 * ============================================================================
 * 版权所有 2016 。
 *
 * @author fallenpanda
 * @version 1.0 2016-08-09 。
 * ============================================================================
 */
@Controller
@RequestMapping(value = "/main/post")
public class PostController extends BaseController {

    private static final long serialVersionUID = -8505548616544173668L;

    @Autowired
    private PostService postService;
    @Autowired
    private DepartmentService departmentService;

    /**
     * 新建页面
     */
    @RequestMapping(value = "create", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String create(@CurrentUser User user) {

        return "/main/company/post_input";
    }

    /**
     * 编辑页面
     */
    @RequestMapping(value = "update/{keyId}", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String update(@CurrentUser User user, Model model,
                         @PathVariable String keyId) {

        model.addAttribute("keyId", keyId);
        return "/main/company/post_input";
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user,
                       @RequestParam(required = false) String keyId,
                       Post post) {
        // 必填校验
        if (StringUtils.isBlank(post.getName())) {
            return resultService.fail("岗位名称不能为空");
        }

        if (StringUtils.isBlank(keyId)) {// 保存
            return ajaxJson(postService.createEntity(user, post));
        } else {// 修改
            return ajaxJson(postService.updateEntity(user, keyId, post));
        }
    }

    /**
     * 初始化表单
     */
    @RequestMapping(value = "init", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object init(@CurrentUser User user) {
        Post post = new Post();

        Map<String, Object> dataMap = postService.getDetailMap(post);

        Result result = resultService.successWithData(dataMap);

        return ajaxJson(result);
    }

    /**
     * 获取详情
     */
    @RequestMapping(value = "read/{keyId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object read(@CurrentUser User user,
                       @PathVariable String keyId) {
        Post post = postService.get(keyId);
        if (post == null){
            post = new Post();
        }

        Map<String, Object> dataMap = postService.getDetailMap(post);

        Result result = resultService.successWithData(dataMap);

        return ajaxJson(result);
    }

    /**
     * 操作
     */
    @RequestMapping(value = "method/{method}/{keyId}", method = RequestMethod.POST)
    public Object method(@CurrentUser User user,
                         @PathVariable String method,
                         @PathVariable String keyId) {
        Result result = postService.methodEntity(user, method, keyId);

        return ajaxJson(result);
    }

    /**
     * 列表
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user,
                                    JqGridPager pager,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {
        Company company = user.getCompany();

        // 排序
        Order order = null;
        if (StringUtils.isNotBlank(pager.getSidx()) && StringUtils.isNotBlank(pager.getSord())) {
            order = Order.order(pager.getSidx(), SearchEnum.OrderType.valueOf(pager.getSord()));
        }

        List<Rule> rules = getSearchFilterRules(pager.getSearch(), filters);
        SearchResultPaging searchResult = postService.pagingPost(PageHelp.page(pager.getPage(), pager.getRows()), rules, order, company, BaseEnumManager.StateEnum.Enable);

        List<Post> postList = searchResult.getList();

        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();

        for (Post entity : postList) {
            Map<String, Object> map = postService.getListMap(entity);
            dataRows.add(map);
        }

        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());

        return data;
    }

    /**
     * 列表
     */
    @RequestMapping(value = "list_select", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object list_select(@CurrentUser User user) {
        Company company = user.getCompany();

        SearchResultList searchResult = postService.listPost(null, null, company, BaseEnumManager.StateEnum.Enable);

        List<Post> postList = searchResult.getList();

        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();

        for (Post entity : postList) {
            Map<String, Object> map = postService.getListMap(entity);
            dataRows.add(map);
        }

        return ajaxJson(resultService.successWithData(dataRows));
    }

    /**
     * 选择岗位
     */
    @RequestMapping(value = "dialog", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String dialog(@CurrentUser User user, Model model,
                         String departmentId) {

        model.addAttribute("departmentId", departmentId);
        return "/main/company/post_dialog";
    }

    /**
     * 选择岗位
     */
    @RequestMapping(value = "dialogs", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String dialogs(@CurrentUser User user,@RequestParam(required = false) String sids, Model model) {
        model.addAttribute("sids",sids);
        if (StringUtils.isNotBlank(sids)) {
            String[] pids = StringUtils.split(sids,",");
            ArrayList<Post> posts = new ArrayList<Post>();
            for (String pid : pids) {
                Post post = postService.get(pid);
                posts.add(post);
            }
            model.addAttribute("selectedPosts",posts);
        }
        return "/main/company/post_dialogs";
    }
}
